package cn.tedu.controller;

import cn.tedu.entity.User;
import cn.tedu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author JokerQiu
 * @date 2021年12月16日 10:45
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("登陆请求被执行");
        /*
         * 1.获取参数
         * 2.验证用户
         * 3.返回结果
         */
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        //进行登陆
        User user = userService.login(email, password);
        //返回结果
        if (user != null) {
            //成功登陆
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            session.setAttribute("nickname", user.getNickname());
            resp.sendRedirect("bookList");
        } else {
            req.setAttribute("errorMsg", "用户名或密码错误！");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }
}
